<template>
  <div>
    <FixedOperation>
      <!-- 内容 -->
      <el-row :gutter="20">
        <!--产品分类-->
        <el-col :span="24" :xs="24">
          <div class="text-right">
            <el-button type="primary" @click="handleSubmit">保存</el-button>
            <el-button @click="handleReturn(true)">返回</el-button>
            <!-- <el-button icon="Refresh" @click="handleReset(form)"
              >重置</el-button
            > -->
          </div>
        </el-col>
      </el-row>
    </FixedOperation>
    <div class="app-container warehouse-form">
      <el-form
        ref="form"
        :model="formData"
        label-width="140px"
        :rules="formRules"
      >
        <el-row>
          <el-col :span="12" :offset="5">
            <el-form-item label="仓库编号" prop="number">
              <el-input
                v-model="formData.number"
                placeholder="请输入仓库编号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="5">
            <el-form-item label="仓库名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入仓库名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="5">
            <el-form-item label="仓库地址" prop="address">
              <el-input
                v-model="formData.address"
                placeholder="请输入仓库地址"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="5">
            <el-form-item label="库管员" prop="_managerIdArr">
              <el-select
                class="w-full"
                v-model="formData._managerIdArr"
                placeholder="请选择库管员"
                multiple
                @focus="selectUserFn('_managerIdArr')"
              >
                <el-option
                  v-for="item in userOption['managerIdArr']"
                  :key="item.uuid"
                  :label="item.label"
                  :value="item.uuid"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="5">
            <el-form-item label="所属单位" prop="unit">
              <el-tree-select
                class="w-full"
                v-model="formData.unit"
                placeholder="请选择所属单位"
                default-expand-all
                :data="companyOption"
                :props="{
                  value: 'id',
                  label: 'label',
                  children: 'children'
                }"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="5">
            <el-form-item label="类型" prop="type">
              <el-select
                class="w-full"
                v-model="formData.type"
                placeholder="请选择类型"
              >
                <el-option
                  v-for="item in warehouse_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="5">
            <el-form-item label="零出库控制" prop="zeroExitControl">
              <el-select
                class="w-full"
                v-model="formData.zeroExitControl"
                placeholder="请选择零出库控制"
              >
                <el-option
                  v-for="item in zero_exit_controller"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="5">
            <el-form-item label="备注信息" prop="remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 人员弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParam"
      @ok="selectDialogData"
      @close="
        val => {
          dialogParam.isDialog = false
        }
      "
    ></SelectDialog>
  </div>
</template>
<script setup name="WarehouseForm">
import { reactive, toRefs, ref, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import FixedOperation from '@/components/FixedOperation'
import useCommonStore from '@/store/modules/common'
import { setWarehouse, getWarehouse } from '@/api/warehouseManage/warehouse'
import {
  companyOption //归属公司
} from '@/hooks/dict/order'
import useTagsViewStore from '@/store/modules/tagsView'
import { getTreeNodeByParam, getPricipalId } from '@/utils/commo'

const router = useRouter()
const route = useRoute()
const commonStore = useCommonStore()
const { proxy, type } = getCurrentInstance()
const userOption = ref({}) //人员下拉
const { warehouse_type, zero_exit_controller } = proxy.useDict(
  'warehouse_type', //仓库类型
  'zero_exit_controller' //零出库控制
)

const props = defineProps({
  warehouseId: {
    type: [Number, String],
    require: true
  }
})
const data = reactive({
  formData: {
    _managerIdArr: []
  },

  formRules: {
    number: [
      {
        required: true,
        message: '请输入仓库编号',
        trigger: 'blur'
      }
    ],
    name: [
      {
        required: true,
        message: '请输入仓库名称',
        trigger: 'blur'
      }
    ],
    address: [
      {
        required: true,
        message: '请输入仓库地址',
        trigger: 'blur'
      }
    ],
    _managerIdArr: [
      {
        required: true,
        message: '请选择收款人员',
        trigger: 'change'
      }
    ],
    unit: [
      {
        required: true,
        message: '请选择归属单位',
        trigger: 'change'
      }
    ]
  },

  dialogParam: {} /* 人员弹窗框参数 */
})
const { formData, formRules, dialogParam } = toRefs(data)
// watch(
//   () => data.formData.productInfoList,
//   (newVal, oldValue) => {
//     let price = 0
//     formData.value.productInfoList.forEach(e => {
//       if (e.id) {
//         price = e.price * e.num + price
//       }
//     })
//     formData.value.price = price
//   },
//   { deep: true }
// )
watchEffect(() => {
  if (route.query.warehouseId && route.name == type.name) {
    // console.log('instance.type.name-->', type.name)
    getFormData(route.query.warehouseId)
  }
  if (props.warehouseId) {
    // console.log('props.warehouseId==>', props.warehouseId)
    getFormData(props.warehouseId)
  }
})
/** 获取产品详情
 * @param {number}  id 表单id
 */
function getFormData(id) {
  proxy.$modal.loading('加载中')
  getWarehouse(id).then(async res => {
    let resData = {}
    resData = res.data
    formData.value = resData
    proxy.$modal.closeLoading()
    // 获取库管员
    await getDefaultUserInfo(
      formData.value.managerIdArr,
      '_managerIdArr',
      'managerIdArr'
    )
  })
}

// 初始化
function init() {}
// 保存
function handleSubmit(e) {
  console.log('保存-<>', formData.value)
  if (formData.value._managerIdArr.length > 0) {
    // formData.value.managerIdArr = getPricipalId(
    //   userOption.value['managerIdArr'],
    //   formData.value._managerIdArr
    // )
    formData.value.managerIdArr = formData.value._managerIdArr.map(e =>
      e.replace('U', '')
    )
  }
  proxy.$refs.form.validate((valid, msg) => {
    if (valid) {
      setWarehouse(formData.value).then(res => {
        // proxy.$modal.msgSuccess(formData.value.id ? '修改成功' : '新增成功')
        // handleReturn(!formData.value.id)
        // 保存接口才有
        proxy.useReturn(
          '',
          () => {
            //返回上一步
            handleReturn(true)
          },
          async () => {
            //继续
          }
        )
        getFormData(res.data.id)
        // formData.value = res.data
      })
    }
  })
}

function handleReset() {
  console.log('清除')
  formData.value = {}
  proxy.resetForm('sortRef')
  //   proxy.$refs.form.resetForm()
}

/* 人员选择
 * @param {string}  keyName managerIdArr:库管员
 */
function selectUserFn(keyName) {
  dialogParam.value.type = keyName
  dialogParam.value.title = '请选择库管员'
  dialogParam.value.isDialog = true
  dialogParam.value.multiple = true
  dialogParam.value.nodeKey = 'uuid'
  dialogParam.value.defaultCheckedKeys = formData.value[keyName]
  dialogParam.value.dataType = 'person'
}
// 人员选择确定
const selectDialogData = val => {
  switch (val.type) {
    case '_managerIdArr':
      userOption.value.managerIdArr = val.selectData
      formData.value.managerNameArr = val.labelData
      formData.value._managerIdArr = val.defaultCheckedKeys
      break
  }
}

// 根据当前用户id获取uuid
async function getDefaultUserInfo(val, fieldName, selectArr) {
  userOption.value[selectArr] = []
  let id = ''
  if (val) {
    id = val
  }
  //获取部门人员数据
  const deptUserData = await commonStore.getUseTreeData()
  if (Array.isArray(id)) {
    formData.value[fieldName] = []
    id.forEach(item => {
      let obj = getTreeNodeByParam(deptUserData, item, 'id', [])
      let isH = userOption.value[selectArr].some(userItem => userItem.id == id)
      if (!isH) {
        userOption.value[selectArr].push(...obj)
      }
      let isHf = formData.value[fieldName].some(
        userItem => userItem == obj[0].uuid
      )
      if (!isHf) {
        formData.value[fieldName].push(obj[0].uuid)
      }
    })
    console.log('formData.value[fieldName]==>', formData.value[fieldName])
    console.log('userOption.value[selectArr]==>', userOption.value[selectArr])
  } else {
    //根据当前用户id获取uuid
    let obj = getTreeNodeByParam(deptUserData, id, 'id', [])
    userOption.value[selectArr] = obj
    formData.value[fieldName] = obj[0].uuid
  }
}

// 返回、关闭页面
function handleReturn(isReturn) {
  if (isReturn) {
    useTagsViewStore().delView(router.currentRoute.value)
    router.go(-1)
  }
  // router.push({ path: url, query: data })
  //   proxy.$refs.form.clearValidate()
}

init()
</script>
<style scoped>
.form-title {
  color: #111111;
}
.warehouse-form:deep(.form-title:before) {
  content: '▋';
  display: inline-block;
  color: #409eff;
}
</style>
